<?php
/*
 * Backend support for BeeLine.mxml
 * 
 */
require_once(dirname(__FILE__) . "/dbcon.php");
require_once(dirname(__FILE__) . "/functions.inc.php");
require_once(dirname(__FILE__) . "/XmlSerializer.class.php");

function insertHive() 
{
	global $conn;

	$rc = mysql_query	("	
		INSERT INTO hives (hive_id, finder_id, species_id, hive_type_id, height, age_years, added_ts, find_dt, longitude, latitude) 
		VALUES
			(3, 1, 1, 1, 10, 5, DEFAULT, '2008-06-29', 35.739067, -78.858694),
		;");
	
	if (!$rc)
	{
		$out = array(
			"data" => array("error" => mysql_error()), 
			"metadata" => array()
		);
	}

	return $out;
}

function getSpecies()
{
	global $conn;
	$result = mysql_query("select species_id, common_name from bee_species", $conn);
	$return = array();
	while ($row = mysql_fetch_assoc($result)) 
	{
		array_push($return, $row);
	}
	return $return;
}
	

function getHives() 
{
	global $conn;

	$rscount = mysql_query("SELECT count(hive_id) AS cnt FROM `hives`"); 
	$row_rscount = mysql_fetch_assoc($rscount);
	$totalrows = (int) $row_rscount["cnt"];
	
	$pageNum = (int)@$_REQUEST["pageNum"];
	$pageSize = (int)@$_REQUEST["pageSize"];
	$start = $pageNum * $pageSize;

	$query_recordset = "
		select 	h.find_dt,
				h.age_years,
				h.height,
				h.latitude,
				h.longitude,
				s.common_name, 
				t.type_name 
		from 	hives h, 
				hive_types t,
				bee_species s
		where 	h.hive_type_id = t.hive_type_id
		and 	h.species_id = s.species_id 
	";
	
	//if we use pagination, add the limit clause
	if ($pageNum >= 0 && $pageSize > 0) 
	{	
		$query_recordset = sprintf("%s LIMIT %d, %d", $query_recordset, $start, $pageSize);
	}

	$recordset = mysql_query($query_recordset, $conn);
	
	$toret = array();
	while ($row_recordset = mysql_fetch_assoc($recordset)) 
	{
		array_push($toret, $row_recordset);
	}
	
	$toret = array(
		"data" => $toret, 
		"metadata" => array (
			"totalRows" => $totalrows,
			"pageNum" => $pageNum
		)
	);

	return $toret;
}

function invalidCmd ()
{
	$out = array(
		"data" => array("error" => "ERROR: Invalid method."), 
		"metadata" => array()
	);
	
	return $out;
}


mysql_select_db($database_conn, $conn);

switch (@$_REQUEST["method"]) 
{
	case "get_hives":
		$out = getHives();
	break;
	
	case "get_species":
		$out = getSpecies();
	break;
	
	case "insert_hive":
		$out = insertHive();
	break;
	
	default:
		$out = invalidCmd();		
}

$serializer = new XmlSerializer();
echo $serializer->serialize($out);
die();

?>